package juc.CAS;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * AtomicStampedReference
 */
@Slf4j
public class demo3 {
    //新建AtomicStampedReference对象，初始值为“A”，版本号为0
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
    public static void main(String[] args) throws InterruptedException {
        //获取值
        String reference = ref.getReference();
        //获取版本号
        int stamp = ref.getStamp();
        log.debug("初始stamp：" +stamp);
        other();
        //睡眠1s等待其他线程修改数据
        TimeUnit.SECONDS.sleep(1);
        log.debug("现在的stamp:"+ref.getStamp());
        //                                  由于版本号不一样了，更新失败
        log.debug("A->C {}",ref.compareAndSet(reference,"C",stamp,stamp+1));
    }

    private static void other() throws InterruptedException {
        new Thread(() -> {
            log.debug("change A->B {}", ref.compareAndSet(ref.getReference(), "B", ref.getStamp(), ref.getStamp() + 1));
            log.debug("更新版本为 {}", ref.getStamp());
        }, "t1").start();

        new Thread(() -> {
            log.debug("change B->A {}", ref.compareAndSet(ref.getReference(), "A", ref.getStamp(), ref.getStamp() + 1));
            log.debug("更新版本为 {}", ref.getStamp());
        }, "t2").start();
    }
}

